<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" label="ID" align="center" width="80px">
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column label="参数类型" align="center" width="120px">
        <template v-slot="{row}">
          <span>{{ row.globalParamType === 0 ? '静态参数' : (row.globalParamType === 2 ? '用户参数' : (row.value === 'TimeStamp' ? '时间戳' : (row.value === 'Random' ? '随机数' : '其他'))) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="参数名" align="center">
        <template v-slot="{row}">
          {{ row.paramName }}
        </template>
      </el-table-column>
      <el-table-column label="参数值" align="center">
        <template v-slot="{row}">
          <span>{{ row.globalParamType !== 1 ? row.value : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参数长度" align="center" width="100px">
        <template v-slot="{row}">
          {{ row.globalParamType === 1 ? (row.length === 0 ? '' : row.length) : '' }}
        </template>
      </el-table-column>
      <el-table-column label="作用域" align="center" width="120px">
        <template v-slot="{row}">
          <span v-if="row.globalParamType === 1">{{ row.globalParamScope === 1 ? '用例唯一' : '套件唯一' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center">
        <template v-slot="{row}">
          {{ row.desc }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180px">
        <template v-slot="{row, $index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="del(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
        <el-alert style="margin-bottom: 10px" title="规则提示" type="info" close-text="Get!">
          <div><b>1、动态参数：当参数类别为时间戳，且给定的长度为0时，将返回毫秒时间戳，如需指定长度请务必修改。</b></div>
          <div>2、用户参数：不同用户参数名相同，参数值不同，一般用于处理账号密码等加密数据。</div>
          <div>3、静态参数：固定值，永远保持不变。</div>
        </el-alert>
        <el-form-item label="参数类型" prop="paramTypeOptions">
          <el-select v-model="temp.globalParamType" placeholder="请选择" @change="handleChange($event)">
            <el-option
              v-for="item in paramTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div v-if="temp.globalParamType === 0">
          <el-form-item label="参数名" prop="paramName">
            <el-input v-model="temp.paramName" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="参数值" prop="value">
            <el-input v-model="temp.value" placeholder="请输入内容" />
          </el-form-item>
        </div>
        <div v-if="temp.globalParamType === 1">
          <el-form-item label="参数名" prop="paramName">
            <el-input v-model="temp.paramName" placeholder="请输入参数名" />
          </el-form-item>
          <el-form-item label="参数类别" prop="value">
            <el-select v-model="temp.value" placeholder="请选择">
              <el-option
                v-for="item in paramFunOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="长度" prop="length">
            <el-input-number v-model="temp.length" :min="0" :max="50" />
          </el-form-item>
          <el-form-item label="作用域" prop="globalParamScope">
            <el-select v-model="temp.globalParamScope" placeholder="请选择">
              <el-option
                v-for="item in scopeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div v-if="temp.globalParamType === 2">
          <el-form-item label="参数名" prop="paramName">
            <el-input v-model="temp.paramName" placeholder="请输入参数名" />
          </el-form-item>
          <el-form-item label="参数值" prop="value">
            <el-input v-model="temp.value" placeholder="请输入参数值" />
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="temp.desc" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { create, update, del, list } from '@/api/functional_test/global_param'

export default {
  data() {
    const validateParamName = (rule, value, callback) => {
      var reg = RegExp(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/)
      if (value.length === 0) {
        callback(new Error('请输入参数名称'))
      } else if (value.length >= 50) {
        callback(new Error('参数名 长度不能超过 50 个字符'))
      } else if (value.match(reg)) {
        callback(new Error('参数名 不能包含特殊字符'))
      } else {
        callback()
      }
    }
    return {
      paramTypeOptions: [{
        value: 0,
        label: '静态参数'
      }, {
        value: 1,
        label: '动态参数'
      }, {
        value: 2,
        label: '用户参数'
      }],
      paramFunOptions: [{
        value: 'TimeStamp',
        label: '时间戳'
      }, {
        value: 'Random',
        label: '随机数'
      }],
      scopeOptions: [{
        value: 1,
        label: '用例唯一'
      }, {
        value: 2,
        label: '套件唯一'
      }],
      list: null,
      listLoading: true,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        paramName: [
          { required: true, trigger: 'change', validator: validateParamName }
        ],
        value: [
          { required: true, message: '必填项，请补充完整', trigger: 'change' },
          { max: 1024, message: '参数值 长度不能超过 1024 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleChange(event) {
      this.temp.globalParamType = event
      this.temp.paramName = ''
      this.temp.value = ''
      this.temp.length = 10
      this.temp.projectId = this.$store.getters.projectId
      this.temp.globalParamScope = 1
    },
    fetchData() {
      this.listLoading = true
      list(this.$store.getters.projectId).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    handleCreate() {
      this.temp = {
        id: 0,
        globalParamType: 0,
        paramName: '',
        value: '',
        length: null,
        uid: null,
        key: null,
        projectId: this.$store.getters.projectId,
        globalParamScope: 2
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制行数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.temp).then((res) => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    del(row, index) {
      this.$confirm('是否删除此参数?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    }
  }
}
</script>
